﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.MicroKernel.Facilities;
using System.Reflection;
using System.Web.Routing;
using System.Web.Mvc;
using Wolfbyte.Core.Mvc.Factories;
using Castle.MicroKernel.Registration;

namespace Wolfbyte.Core.Mvc.Facilities
{
    public class MvcSupportFacility : AbstractFacility
    {
        protected override void Init()
        {
            if (FacilityConfig != null)
                Configure(new MvcSupportFacilityConfig(FacilityConfig));
            ControllerBuilder.Current.SetControllerFactory(new MicroKernelControllerFactory(Kernel));
        }

        public void Configure( MvcSupportConfiguration configuration )
        {
            if( configuration == null )
                throw new ArgumentException("Facility Configuration cannot be null", "configuration");
            foreach (var controllerType in configuration.ControllerTypes)
                RegisterController(controllerType);
            foreach (var routeRegistrar in configuration.RouteRegistrars)
                routeRegistrar.RegisterRoutes(RouteTable.Routes);
        }

        #region Controller Registration

        public void RegisterControllers(Assembly assembly)
        {
            foreach (var controllerType in assembly.GetExportedTypes())
                RegisterController(controllerType);
        }

        public void RegisterController(Type controllerType)
        {
            var controllerKey = controllerType.Name.ToLower();
            if (IsControllerType(controllerType))
                Kernel.Register(
                    Component
                    .For<IController>()
                    .Named(controllerKey)
                    .ImplementedBy(controllerType)
                    .LifeStyle.Transient
                );
        }

        private static bool IsControllerType(Type controllerType)
        {
            return
                controllerType.IsClass
                && controllerType.GetInterface("IController") != null;
        }

        #endregion

    }
}
